import Toast from '../../miniprogram_npm/@vant/weapp/toast/toast'
import config from '../../config/index'
import { getAccessToken, getPhoneNumber, AccessToken } from '../../api/wxapi/index'
import { wxLogin, checkExpireVip, getUserDetail } from '../../api/wxuser/index'
import { setToken, setUserInfo } from '../../utils/storage'

Page({
  data: {
    //同意阅读协议
    agree: false,
    phoneInfo: {} as PhoneInfo
  },
  onLoad() {
  },
  login(e: any) {
    if(!e.detail.code) {
      Toast('已拒绝授权')
      return
    }
    if(this.data.agree === false) {
      Toast('请勾选并阅读协议')
      return
    }
    wx.showLoading({title: '登录中'})
    getAccessToken(config.appid, config.secret)
    .then((res) => {
      const body: { code: string } = {
        code: e.detail.code
      }
      let token = res.data as AccessToken
      getPhoneNumber(token.access_token, body)
      .then(async (res: any) => {
        this.setData({
          phoneInfo: res.data.phone_info as PhoneInfo
        })
        const data = {
          phone: this.data.phoneInfo.phoneNumber
        }
        wxLogin(data).then((res: any) => {
          if(res.statusCode === config.CREATED_CODE) {
            const { token, user }  = res.data
            setToken(token)
            const id = user.id
            //检查vip是否过期
            checkExpireVip(id).then((res) => {
              if(res.statusCode === config.SUCCESS_CODE) {
                //过期就更新用户信息
                if(res.data) {
                  getUserDetail(id).then((r) => {
                    if(r.statusCode === config.SUCCESS_CODE) {
                      setUserInfo(r.data)
                    }
                  })
                } else {
                  setUserInfo(user)
                }
              }
            })
            wx.reLaunch({
              url: '/pages/index/index',
              success: () => {
                wx.hideLoading()
                wx.showToast({title: '登录成功', icon: 'success'})
              }
            })
          } else {
            wx.hideLoading()
            wx.showToast({title: res.message, icon: 'error'})
          }
        })
        
      })
    })
  },
  onChange(event: any) {
    this.setData({
      agree: event.detail,
    });
  },
  //跳转隐私政策
  toPolicy() {
    wx.downloadFile({
      url: config.BaseUrl + '/files/policy.pdf',
      success: (res) => {
        wx.openDocument({
          filePath: res.tempFilePath
        })
      } 
    })
  },
  //跳转会员服务协议
  toProtocol() {
    wx.downloadFile({
      url: config.BaseUrl + '/files/protocol.pdf',
      success: (res) => {
        wx.openDocument({
          filePath: res.tempFilePath
        })
      } 
    })
  }
})